<template>
  <div>
    <b-table
      ref="table"
      :columns="columns"
      :out-loading="loading"
      :request="loadData"
      :del-func="delFunc"
      :disabled="!hideBuquBtn()"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      :export-config="{use:true,select:'物资效益分析招标物资明细',all:'物资效益分析招标物资明细'}"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          v-if="hideBuquBtn()"
          @click="openDialog()"
        >
          添加行
        </a-button>
      </template>
      <template
        slot="suffix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          @click="openDialog(downloadApi)"
        >
          标准模板下载
        </a-button>
        <ExcelImportButton
          v-if="state !== 3"
          @handleSubmit="importFunc"
        />
      </template>
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['enterData', 'enterNum', 'settleAmount','purchaseAmount','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="state !== 3">
            <a-date-picker
              v-if="col === 'enterData'"
              v-model="record.enterData"
              class="requiredFormItem"
              value-format="YYYY-MM-DD"
              type="date"
              @change="handleChange($event, record, col)"
            />
            <BaseInput
              v-else-if="col === 'remark'"
              v-model="record.remark"
              @blur="handleChange($event.target.value, record, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'enterNum' "
              v-model="record[col]"
              class="requiredFormItem"
              :precision="3"
              @blur="handleChange($event.target.value, record, col)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              class="requiredFormItem"
              :precision="2"
              @blur="handleChange($event.target.value, record, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import benefitAnalysis from '@/api/material/benefitAnalysis/defalut'
import moment from 'moment'

export default {
  props: {
    state: {
      type: Number
    },
    id: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      totalSize: 0,
      columns: [
        { title: '序号', scopedSlots: { customRender: 'index' }, width: 70 },
        { title: '物资名称', dataIndex: 'materialName', width: 200 },
        { title: '物料编码', dataIndex: 'materialCode', width: 100 },
        { title: '规格型号', dataIndex: 'materialModel', width: 200 },
        { title: '单位', dataIndex: 'materialUnit', width: 100 },
        { title: '进场日期', dataIndex: 'enterData', scopedSlots: { customRender: 'enterData' }, width: 150 },
        { title: '进场数量', dataIndex: 'enterNum', scopedSlots: { customRender: 'enterNum' }, width: 120 },
        { title: '发包人单价（元）', dataIndex: 'settleAmount', scopedSlots: { customRender: 'settleAmount' }, width: 150 },
        { title: '发包人金额', dataIndex: 'sumSettle', width: 110 },
        { title: '采购单价（元）', dataIndex: 'purchaseAmount', scopedSlots: { customRender: 'purchaseAmount' }, width: 140 },
        { title: '采购金额', dataIndex: 'sumPurchase', width: 100 },
        { title: '物资采购效益', dataIndex: 'sumBenefitAnalysis', width: 120 },
        { title: '采购成本降低率', dataIndex: 'sumCostRate', width: 140 },
        { title: '备注', dataIndex: 'remark', scopedSlots: { customRender: 'remark' }, width: 140 }
      ],
      downloadApi: benefitAnalysis.downExcel,
      delFunc: benefitAnalysis.deleteByDetails,
      loadData: params => benefitAnalysis.findListByDetails(Object.assign(params, { beneficialId: this.id }))
    }
  },
  methods: {
    async importFunc(e) {
      // this.$console(e)
      let newTable = []
      let checkRes = true
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '进场数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '采购单价（元）' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '发包人单价（元）' && typeof row[rowKey] !== 'number') checkRes = false
            // if (rowKey === '进场日期') {
            //   temp[dataIndex] = typeof row[rowKey] == 'number' ? this.$formatDate(row[rowKey],'yyyy-MM-dd') : moment(new Date(row[rowKey])).format('YYYY-MM-DD');
            // } else {
            //   temp[dataIndex] = row[rowKey]
            // }
          }
        }
        temp.materialContractId = this.id
        temp.beneficialId = this.id
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning('数据格式错误！')
      }
      // this.$console(newTable)
      this.loading = true
      let res = await benefitAnalysis.createByDetailsBatch(newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === '操作成功！') {
          this.$noticeSuccess('导入成功！')
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
        this.$refs.table.getData(null, true)
      }
    },
    async openDialog(downloadApi) {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        let res = await benefitAnalysis.findListByDetails({
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          beneficialId: this.id
        })
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      if (downloadApi) {
        this.$refs.detailDialog.download(allData, downloadApi)
      } else {
        this.$refs.detailDialog.open(allData)
      }
    },
    async createList(selectRows) {
      let params = []
      selectRows.map(selectRow => {
        params.push(
          {
            materialName: selectRow.materialName,
            materialCode: selectRow.materialCode,
            materialModel: selectRow.specificationModel,
            unit: selectRow.unitId,
            materialContractId: this.id,
            materialId: selectRow.id,
            beneficialId: this.id
          })
      })
      this.loading = true
      let res = await benefitAnalysis.createByDetailsBatch(params)
      if (res.code === 200) {
        this.$refs.table.getData(null, true)
      }
      this.loading = false

    },
    handleChange(val, row, col) {
      if (col === 'enterNum' || col === 'settleAmount') {
        if (row['enterNum'] && row['settleAmount']) {
          //发包人金额 = 进场数量 * 发包人单价
          row['sumSettle'] = Number(row['enterNum']) * Number(row['settleAmount'])
          row['sumSettle'] = row['sumSettle'].toFixed(2)
        } else {
          row['sumSettle'] = 0
        }
      }
      if (col === 'enterNum' || col === 'purchaseAmount') {
        if (row['enterNum'] && row['purchaseAmount']) {
          //采购金额 = 进场数量 * 采购单价
          row['sumPurchase'] = Number(row['enterNum']) * Number(row['purchaseAmount'])
          row['sumPurchase'] = row['sumPurchase'].toFixed(2)
        } else {
          row['sumPurchase'] = 0
        }
      }
      if (!this.$isEmpty(row['sumSettle']) && !this.$isEmpty(row['sumPurchase'])) {
        //物资采购效益 = 发包人金额 - 采购金额
        row['sumBenefitAnalysis'] = Number(row['sumSettle']) - Number(row['sumPurchase'])
        row['sumBenefitAnalysis'] = row['sumBenefitAnalysis'].toFixed(2)
      }

      if (row['sumBenefitAnalysis'] && row['sumSettle']) {
        //采购成本降低率 = 物资采购效益 / 发包人金额
        row['sumCostRate'] = Number(row['sumBenefitAnalysis']) / Number(row['sumSettle'])
        row['sumCostRate'] = row['sumCostRate'].toFixed(2)
      }
      this.save(row)
      // this.$console(row)
    },
    async save(target) {
      // if (target.purchaseAmount === null) {
      //   return this.$message.warning('采购单价不能为空')
      // }
      // if (!target.enterData) {
      //   return this.$message.warning('进场日期不能为空')
      // }
      // if (!target.enterNum) {
      //   return this.$message.warning('进场数量不能为空')
      // }
      // if (!target.settleAmount) {
      //   return this.$message.warning('发包人单价不能为空')
      // }
      let res
      if (target.id) {
        res = await benefitAnalysis.editByDetails({}, target)
      } else {
        res = await benefitAnalysis.createByMain({}, target)
      }
      if (res.code !== 200) this.$noticeWarning(res.message)
    }
  }
}
</script>
